package com.liangzong.betspider.task;

import com.liangzong.betspider.config.ChromeDriverConfig;
import com.liangzong.betspider.service.ManageDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import static com.liangzong.betspider.utils.SpiderInfoUtil.*;

@Component
@Slf4j
@Configuration
public class StartSpiderTask implements ApplicationRunner {

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("close driver");
            for (Process process : threads) {
                try {
                    process.stopWork();
                } catch (InterruptedException e) {
                    log.error(e.getMessage(),e);
                }
            }
            threads.clear();
        }));
    }
    @Autowired
    ChromeDriverConfig chromeDriverConfig;

    @Autowired
    ManageDataService manageDataService;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }

    //启动浏览器 "C:\Program Files\Google\Chrome\Application\chrome.exe"  --remote-debugging-port=9222 --user-data-dir="D:\auto\test"
    //输入 https://www.365365304.com/#/IP/B1
    public void start() throws Exception {
        //处理数据
        Thread sync = new Thread(new SyncDataTask(manageDataService));
        sync.setDaemon(true);
        sync.start();

        startWorks();
    }

    public void startWorks() throws InterruptedException {
        int port = chromeDriverConfig.getPort();
        int minWorks = chromeDriverConfig.getMinWorks();
        int watchNum = chromeDriverConfig.getWatchNum();
        int overTime = chromeDriverConfig.getOverTime();
        long pauseTime = chromeDriverConfig.getPauseTime();
        //线程管理

        for (int i = 0; i < minWorks; i++) {
            Process newStartProcess = createNewProcess(i, port, pauseTime, overTime);
            newStartProcess.setDaemon(true);
            newStartProcess.start();
            threads.add(newStartProcess);
            Thread.sleep(20 * 1000L);
        }
    }


    public Process createNewProcess(int index, int port, long pauseTime, int overTime) {
        boolean reverse = (index % 2 == 0);
        int startPort = port + index;
        Process startProcess = new Process(this, reverse, startPort, pauseTime, overTime);
        return startProcess;
    }

}
